package cn.sxw.android.base.kt

import android.graphics.Color
import android.os.Bundle
import android.view.View
import androidx.databinding.ViewDataBinding
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout.OnRefreshListener
import cn.sxw.android.R
import cn.sxw.android.base.mvp.IViewAdvance
import cn.sxw.android.base.provider.CustomStatusPageHelper

/**
 * Created by zhanghai on 2019/1/24.
 * function：
 */
abstract class BaseSwipeKtFragmentAdv<T : ViewDataBinding, V : BaseViewModel> : BaseNormalKtFragmentAdv<T, V>(), IViewAdvance, OnRefreshListener {
    protected var hasMoreData = false
    protected val notDataView: View by lazy(LazyThreadSafetyMode.NONE) {
        CustomStatusPageHelper.makeStatusView(R.mipmap.status_empty, "暂无相关数据")
    }
    protected val errorView: View by lazy(LazyThreadSafetyMode.NONE) {
        CustomStatusPageHelper.makeStatusView(R.mipmap.status_error, "数据加载失败，点击重试。")
    }
    protected val mLoadingView: View by lazy(LazyThreadSafetyMode.NONE) {
        CustomStatusPageHelper.makeLoadingView(getString(R.string.txt_loading_common))
    }

    private var mSwipeRefreshLayout: SwipeRefreshLayout? = null

    protected fun addSwipeRefreshAbility() {
        mSwipeRefreshLayout = binding.root.findViewById(R.id.swipe_refresh_layout_common)
        if (mSwipeRefreshLayout == null) return
        mSwipeRefreshLayout!!.setColorSchemeColors(Color.parseColor("#49b271"))
        mSwipeRefreshLayout!!.setOnRefreshListener(this)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        addSwipeRefreshAbility()
        initStatusPages()
    }

    private fun initStatusPages() {
        notDataView.setOnClickListener { onRefresh() }
        errorView.setOnClickListener { onRefresh() }
        updateStatusPages()
    }

    // 更新状态文字或图标
    open fun updateStatusPages() {
        // 例如：
        // CustomStatusPageHelper.updateTips(notDataView, "自定义无数据提示文案")
    }

    override fun hideLoading() {
        super.hideLoading()
        if (mSwipeRefreshLayout != null) mSwipeRefreshLayout!!.isRefreshing = false
    }

    /**
     * 下拉刷新和加载更多时，不会显示Loading
     */
    override fun showLoading(msg: String) {
        isLoading = true
        // 如果是下拉刷新，不显示Loading框
        if (mSwipeRefreshLayout != null && mSwipeRefreshLayout!!.isRefreshing) return
        // 如果是加载更多，也不显示Loading框
        if (viewModel.currPage > 1) return

        // 显示Loading框
        super.showLoading(msg)
    }

    companion object {
        const val PAGE_SIZE = 15
    }
}